/* eslint-disable no-unused-vars */
/* eslint-disable no-console */
/*
 * @Author: your name
 * @Date: 2020-09-03 16:07:46
 * @LastEditTime: 2020-09-10 17:17:15
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \boot_video\packages\ruien-video-play\src\request.js
 */
import { createHttp } from '@/utils/request'
const maxRequestNum = 2 // 最大同时请求数
let requestNum = 0 // 当前请求数
let waitList = [] // 等待下次请求的列表
let isPause = false // 是否暂停

function requestInterceptors (config) {
  if (!Object.keys(config.params).length) {
    return config
  }

  if (requestNum < maxRequestNum) {
    requestNum++
    return config
  } else {
    waitList.push({ key: config.params.key, url: config.url })
    // eslint-disable-next-line prefer-promise-reject-errors
    return Promise.reject({ data: {}, code: -1 })
  }
}

function requestErrorInterceptors (error) {
  return Promise.reject(error)
}

function responseInterceptors (response) {
  // 对响应数据做点什么
  requestNum--
  if (waitList.length) {
    const item = waitList.shift()
    window.$getVideoBufferList(item.key, item.url)
  }
  return response
}

function responseErrorInterceptors (error) {
  // 对响应错误做点什么
  const err = JSON.parse(JSON.stringify(error))
  if ((err.message && err.message.search(/404/))) {
    waitList.unshift({ key: err.config.params.key, url: err.config.url })
    requestNum--
  }

  // eslint-disable-next-line prefer-promise-reject-errors
  return isPause ? Promise.reject({ code: -2 }) : Promise.reject(error)
}

// 暂停请求
function pauseRequest (source) {
  if (waitList.length) {
    isPause = true
    source.cancel()
  }
}
let http = createHttp(null, {
  reqIntercepter: requestInterceptors,
  respIntercepter: responseInterceptors,
  reqErrorInterceptor: requestErrorInterceptors,
  respErrorInterceptor: responseErrorInterceptors
})
// 将取消请求的视频key添加到等待队列中
function setCancelItems (item) {
  waitList.unshift(item)
  requestNum--
}

// 恢复请求
function recoveryRequest () {
  isPause = false
  window.$setSource()
  if (waitList.length) {
    window.$getVideoBufferList(waitList[0].key, waitList[0].url)
  }
}

// 停止请求并且清空等待队列的数据
function clearWaitList (source) {
  source.cancel()
  waitList = []
  requestNum = 0
}

export { http, clearWaitList, pauseRequest, setCancelItems, recoveryRequest }
